﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
using System.IO;

namespace Config.Core.Instructions
{
    /// <summary>
    /// Inserts node(s) into the XML document from an external file.
    /// </summary>
    public class InsertInstruction : IInstruction
    {
        #region Properties
        /// <summary>
        /// Gets or sets the XML comment node for the instruction.
        /// </summary>
        /// <value>The XML comment node.</value>
        public XComment XComment { get; set; }

        /// <summary>
        /// Gets or sets the source file.
        /// </summary>
        /// <value>The source file.</value>
        [InstructionParam(Name = "file", IsOptional = true)]
        public string File { get; set; }
        
        /// <summary>
        /// Gets or sets the XPath of the element to be changed.
        /// </summary>
        /// <value>The XPath of the element.</value>
        [InstructionParam(Name = "xpath", IsOptional = true)]
        public string XPath { get; set; }
        #endregion

        /// <summary>
        /// Runs the instruction against the XML Document.
        /// </summary>
        /// <param name="xDoc">The XML document.</param>
        public void Run(XDocument xDoc)
        {
            if (String.IsNullOrEmpty(XPath))
            {
                using (StreamReader file = new StreamReader(File))
                {
                    XElement element = XElement.Parse(file.ReadToEnd(), LoadOptions.PreserveWhitespace);
                    XComment.ReplaceWith(element);
                    file.Close();
                }
            }
            else
            {
                XDocument xFile = XDocument.Load(File);
                var elements = xFile.XPathSelectElements(XPath);
                XComment.ReplaceWith(elements);
            }
        }
    }
}
